package com.todo.strategy.online.application.mq.receiver;

import com.alibaba.fastjson.JSONObject;
import com.todo.biz.common.enums.CounterTypeEnum;
import com.todo.biz.service.api.request.QueryBizCounterByBizIdRequest;
import com.todo.biz.service.api.response.BizCounterBaseResponse;
import com.todo.common.common.entity.response.BizResponse;
import com.todo.common.common.enums.BusinessSceneEnum;
import com.todo.component.redis.RedisService;
import com.todo.strategy.common.constant.StrategyOnlineKeyBuild;
import com.todo.strategy.online.application.base.apollo.constants.ListenerRabbitConfig;
import com.todo.strategy.online.application.entity.bo.PlatformStrategyCountBO;
import com.todo.strategy.online.application.mq.entity.BizCountMQEntity;
import com.todo.strategy.online.application.remote.BizCounterRemoteService;
import com.todo.strategy.online.application.service.PlatformStrategyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author azhebuxing
 * @date 2024/12/13 01:39
 * @description
 */
@Slf4j
@Component
public class PStrategyCounterReceiver {

    @Resource
    private PlatformStrategyService platformStrategyService;
    @Resource
    private BizCounterRemoteService bizCounterRemoteService;
    @Resource
    private RedisService redisService;

    @RabbitListener(queues = ListenerRabbitConfig.QUEUE_PLATFORM_STRATEGY_COUNT)
    public void receiveMessage(Message message) {
        String messageId = message.getMessageProperties().getMessageId();
        String idempotentKey = StrategyOnlineKeyBuild.PStrategyCounterIdempotentKey(messageId);
        if (redisService.hasKey(idempotentKey)) {
            //当前似乎逻辑为默认执行成功，后续调整ACK即可
            log.info("PStrategyCounterReceiver#receiveMessage 当前状态数据已经处理或处理中，默认消息重试 messageId：{}", messageId);
            return;
        }
        //默认缓存10min
        redisService.set(idempotentKey, "ok", 10 * 60);

        String messageBody = new String(message.getBody());
        BizCountMQEntity entity = JSONObject.parseObject(messageBody, BizCountMQEntity.class);
        if (entity == null) {
            return;
        }
        if (!BusinessSceneEnum.PLATFORM_STRATEGY.equals(entity.getBizScene())) {
            log.error("PStrategyCounterReceiver#receiveMessage 当前数据业务不为内容，数据异常 请及时关注 messageBody：{}", messageBody);
            return;
        }
        QueryBizCounterByBizIdRequest request = new QueryBizCounterByBizIdRequest();
        request.setBizId(entity.getBizId());
        request.setScene(entity.getBizScene());
        BizResponse<List<BizCounterBaseResponse>> bizResponse = bizCounterRemoteService.queryBizCounterByBizId(request);
        if (bizResponse == null || !bizResponse.isSuccess() || CollectionUtils.isEmpty(bizResponse.getData())) {
            log.warn("PStrategyCounterReceiver#receiveMessage 根据业务Id查询，基数数据不存在，请及时关注 messageBody：{}", messageBody);
            return;
        }

        List<BizCounterBaseResponse> bizCounterBaseResponses = bizResponse.getData();
        PlatformStrategyCountBO countBO = new PlatformStrategyCountBO();
        countBO.setPlatformId(entity.getBizId());
        for (BizCounterBaseResponse bizCounterBO : bizCounterBaseResponses) {
            if (CounterTypeEnum.BROWSE.equals(bizCounterBO.getCounterType())) {
                countBO.setSeeCount(bizCounterBO.getCount());
            } else if (CounterTypeEnum.LIKE.equals(bizCounterBO.getCounterType())) {
                countBO.setLikeCount(bizCounterBO.getCount());
            } else if (CounterTypeEnum.COMMENT.equals(bizCounterBO.getCounterType())) {
                countBO.setCommentCount(bizCounterBO.getCount());
            } else if (CounterTypeEnum.COLLECT.equals(bizCounterBO.getCounterType())) {
                countBO.setCollectCount(bizCounterBO.getCount());
            }
        }
        Boolean updated = platformStrategyService.updatePlatformStrategyCount(countBO);
        if (!updated) {
            log.error("PStrategyCounterReceiver#receiveMessage 更新内容统计数据失败，请及时关注 messageBody：{}", messageBody);
        }

    }
}
